package service.impl;

import global.Constants;
import global.beanUtils.BeanUtils;
import global.security.ClientSession;
import global.security.SessionUtils;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.RandomStringUtils;

import service.UserMetaService;
import service.UserService;
import util.DateUtils;
import util.FileUtils;
import util.MD5Utils;
import util.MessageUtils;
import util.ServletHelp;
import util.StringUtils;
import dao.UserDAO;
import domain.User;
import domain.UserMeta;

/**
 * 账户Service实现类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class UserServiceImpl implements UserService {

	/**
	 * 账户DAO
	 * */
	private UserDAO userDao = null;

	/**
	 * 设定账户DAO
	 * */
	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

	/**
	 * 账户元数据Service
	 * */
	private UserMetaService userMetaService = null;

	/**
	 * 设定账户元数据DAO
	 * */
	public void setUserMetaService(UserMetaService userMetaService) {
		this.userMetaService = userMetaService;
	}

	/**
	 * 用户登录验证
	 * @param userId 账户ID
	 * @param password 账户密码
	 * @return JSONObject success 成功标示  message 错误消息 session 用户session信息
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public Map login(String userId, String password) throws Exception {

		// 返回结果
		Map res = new HashMap();
		res.put("success", true);
		// 设置条件
		User paramUser = new User();
		paramUser.setUserId(userId);
		paramUser.setPassword(MD5Utils.getMD5String(password));
		List<User> userList = userDao.selectByCriteria(paramUser);
		if (userList == null || userList.size() != 1) {
			res.put("success", false);
			res.put("message", Constants.E_FAILURE_LOGIN);
		} else {
			// 当前登录User
			User currentUser = userList.get(0);
			if (!Constants.USER_STATUS_1.equals(currentUser.getStatus())) {
				res.put("success", false);
				res.put("message", Constants.E_STOP_LOGIN);
			}else{
				// 获得用户基本信息和配置信息
				currentUser = getUserWithMetaByUserId(currentUser.getUserId());
				// 客户端Session类
				ClientSession cs = SessionUtils.getClientSession(currentUser);
				res.put("session", cs);
			}
		}
		
		return res;
	}

	/**
	 * 根据条件查询用户数量
	 * @Description: 根据条件查询日记数量
	 * @param paramUser 用户
	 * @return int 用户数量
	 */
	public int countByCriteria(User paramUser) {
		// 设置权限条件
		if(Constants.ROLE_CODE_1.equals(SessionUtils.getUserRole())){
			paramUser.setRole("\'"+Constants.ROLE_CODE_2+"\',\'"+Constants.ROLE_CODE_3+"\'");
		}else{
			paramUser.setRole("\'"+Constants.ROLE_CODE_3+"\'");
		}
		int count = userDao.countByCriteria(paramUser);
		return count;
	}

	/**
	 * 根据ID查询用户
	 * @param userId 用户ID
	 * @return User 用户
	 */
	public User selectByPrimaryKey(String userId) {
		User user = userDao.selectByPrimaryKey(userId);
		if(null!=user){
			// 生日
			user.setBirthdayStr(DateUtils.formatDate2Str(user.getBirthday(), DateUtils.DATE_PATTON_1));
		}
		return user;

	}

	/**
	 * 查询账户列表
	 * @param paramUser 用户
	 * @return list 用户列表
	 */
	public List<User> selectByCriteria(User paramUser) {
		List<User> userList = userDao.selectByCriteria(paramUser);
		List<User> results = new ArrayList<User>();
		if(null != userList){
			for(int i=0;i<userList.size();i++){
				User user = userList.get(i);
				user.setBirthdayStr(DateUtils.formatDate2Str(user.getBirthday(), DateUtils.DATE_PATTON_1));
				user.setSex(Constants.SEX_MAP.get(user.getSex()));
				user.setStatus(Constants.USER_STATUS_MAP.get(user.getStatus()));
				user.setCreateDateStr(DateUtils.formatDate2Str(user.getCreateTime(), DateUtils.DATE_TIME_PATTON_1));
				results.add(user);
			}
		}
		return results;
	}

	/**
	 * 查询账户列表带分页
	 * @param paramUser 用户
	 * @return list 用户列表
	 */
	public List<User> selectByCriteriaForPaging(User paramUser) {
		// 设置权限条件
		if(Constants.ROLE_CODE_1.equals(SessionUtils.getUserRole())){
			paramUser.setRole("\'"+Constants.ROLE_CODE_2+"\',\'"+Constants.ROLE_CODE_3+"\'");
		}else{
			paramUser.setRole("\'"+Constants.ROLE_CODE_3+"\'");
		}
		List<User> userList = userDao.selectByCriteriaForPaging(paramUser,
				paramUser.getStart(), paramUser.getLimit());
		List<User> results = new ArrayList<User>();
		if(null != userList){
			for(int i=0;i<userList.size();i++){
				User user = userList.get(i);
				user.setBirthdayStr(DateUtils.formatDate2Str(user.getBirthday(), DateUtils.DATE_PATTON_1));
				user.setRole(Constants.ROLE_MAP.get(user.getRole()));
				user.setSex(Constants.SEX_MAP.get(user.getSex()));
				user.setStatus(Constants.USER_STATUS_MAP.get(user.getStatus()));
				results.add(user);
			}
		}
		return results;
	}

	/**
	 * 添加用户
	 * @param user 用户
	 */
	public void insert(User user) {
		
		// 当前用户ID
		String userId = SessionUtils.getCurrentUserId();
		if(StringUtils.isEmpty(userId)){
			userId = user.getUserId();
		}
		// 密码加密
		user.setPassword(MD5Utils.getMD5String(user.getPassword()));
		// 删除区分：未删除
		user.setDelflag(Constants.DEL_FLAG_1);
		// 系统时间
		Timestamp sysdate = new Timestamp(System.currentTimeMillis());
		user.setCreateUser(userId);
		user.setCreateTime(sysdate);
		user.setUpdateUser(userId);
		user.setUpdateTime(sysdate);
		userDao.insert(user);
	}

	/**
	 * 修改账户信息
	 * @param user 用户
	 */
	public void update(User user) {
		// 系统时间
		Timestamp sysdate = new Timestamp(System.currentTimeMillis());
		user.setUpdateUser(SessionUtils.getCurrentUserId());
		user.setUpdateTime(sysdate);
		userDao.updateByPrimaryKey(user);
	}

	/**
	 * 修改账户信息（包括配置信息）
	 * @param map 用户参数
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public JSONObject update(Map map) throws Exception{
		// 返回结果
		boolean isSuccess = true;
		String message = "";
		
		// 参数设置
		User paramUser = new User();
		BeanUtils.populate(paramUser, map);
		paramUser.setBirthday(DateUtils.formatStr2Date(paramUser.getBirthdayStr(), DateUtils.DATE_PATTON_1));
		
		// 邮箱重复性验证
		List<User> userList = this.selectByCriteria(new User());
		if(null!=userList){
			for (User user : userList) {
				if(paramUser.getEmail().equals(user.getEmail()) && !paramUser.getUserId().equals(user.getUserId())){
					isSuccess = false;
					message = Constants.E_EMAIL_EXIST;
					break;
				}
			}
		}
		
		if(isSuccess){
			// 更新账户基本信息
			this.update(paramUser);
			
			// 更新账户配置信息
			Map userMetaMap = new HashMap();
			userMetaMap.put("theme", (String)map.get("theme"));
			userMetaMap.put("homePage", (String)map.get("homePage"));
			userMetaMap.put("showTodo", (String)map.get("showTodo"));
			userMetaMap.put("showNote", (String)map.get("showNote"));
			userMetaMap.put("showPicture", (String)map.get("showPicture"));
			userMetaMap.put("showAccount", (String)map.get("showAccount"));
			userMetaMap.put("showFeed", (String)map.get("showFeed"));
			userMetaMap.put("showDocument", (String)map.get("showDocument"));
			userMetaMap.put("showSystem", (String)map.get("showSystem"));
			userMetaService.updateByUserIdAndMetaKey(paramUser.getUserId(), userMetaMap);
			
			// 重新设置登录用户Session
			((HttpSession)map.get("session")).removeAttribute("CLIENT_SESSION");
			// 当前登录User
			User currentUser = getUserWithMetaByUserId((String)map.get("userId"));
			// 客户端Session类
			ClientSession cs = SessionUtils.getClientSession(currentUser);
			((HttpSession)map.get("session")).setAttribute("CLIENT_SESSION",cs);
		}
		
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", isSuccess);
		res.put("message", message);
		return res;
	}
	
	/**
	 * 修改账户基本信息
	 * @param userIds 用户IDS
	 * @param map 用户参数
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@SuppressWarnings("unchecked")
	public void update(String userIds, Map map) throws IllegalAccessException, InvocationTargetException{
		// 设置更新参数
		User paramUser = new User();
		BeanUtils.populate(paramUser, map);
		String[] userIdArr = userIds.split(",");
		for (int i = 0; i < userIdArr.length; i++) {
			paramUser.setUserId(userIdArr[i]);
			this.update(paramUser);
		}
	}

	/**
	 * 删除账户信息
	 * @param userIds 用户IDS
	 * @param filePath 用户文件保存路径
	 */
	public void delete(String userIds, String filePath) throws Exception{
		String[] userIdArr = userIds.split(",");
		for (int i = 0; i < userIdArr.length; i++) {
			// 删除用户
			userDao.deleteByPrimaryKey(userIdArr[i]);

			// 删除用户文件目录
			String userFilePath = filePath + "/" +userIdArr[i];
			FileUtils.deleteDirectory(new File(userFilePath));
		}
	}
	
	/**
	 * 注册用户
	 * @param map 参数
	 */
	@SuppressWarnings("unchecked")
	public JSONObject register(Map map) throws Exception{
		boolean isSuccess = true;
		String errorMsg = "";

		// 参数设定
		User paramUser = new User();
		BeanUtils.populate(paramUser, map);
		paramUser.setBirthday(DateUtils.formatStr2Date(paramUser.getBirthdayStr(), DateUtils.DATE_PATTON_1));
		paramUser.setStatus(Constants.USER_STATUS_1);
		if(StringUtils.isEmpty(SessionUtils.getUserRole()) || Constants.ROLE_CODE_3.equals(SessionUtils.getUserRole())){// 普通用户注册时固定角色
			paramUser.setRole(Constants.ROLE_CODE_3);
		}
		// 用户ID
		String userId = map.get("userId").toString();
		// 密码
		String password = map.get("password").toString();
		// 确认密码
		String repassword = map.get("repassword").toString();
		// 验证码
		String verifyCode = map.get("verifyCode").toString();
		String verifyCodeInSession = map.get("verifyCodeInSession").toString();
		
		// 角色验证
		if (Constants.ROLE_CODE_1.equals(SessionUtils.getUserRole())) {// 超级管理员
			if(!(Constants.ROLE_CODE_2.equals(paramUser.getRole()) || Constants.ROLE_CODE_3.equals(paramUser.getRole()))){
				isSuccess = false;
				errorMsg = Constants.E_ROLE_ERROR;
			}
		}else{
			if(!Constants.ROLE_CODE_3.equals(paramUser.getRole())){
				isSuccess = false;
				errorMsg = Constants.E_ROLE_ERROR;
			}
		}
		
		// 密码验证
		if (!password.equals(repassword)) {
			isSuccess = false;
			errorMsg = Constants.E_REPASSWORD;
		}
		
		// 验证码验证
		if (!verifyCode.equals(verifyCodeInSession)) {
			isSuccess = false;
			errorMsg = Constants.E_VERIFY_CODE;
		}
		
		// 账号、邮箱验证
		List<User> userList = this.selectByCriteria(new User());
		if(null!=userList){
			for (User user : userList) {
				if(userId.equals(user.getUserId())){
					isSuccess = false;
					errorMsg = Constants.E_USER_EXIST;
					break;
				}else if(paramUser.getEmail().equals(user.getEmail())){
					isSuccess = false;
					errorMsg = Constants.E_EMAIL_EXIST;
					break;
				}
			}
		}

		if(isSuccess){
			// 添加用户
			this.insert(paramUser);

			// 添加用户配置信息
			Map userMetaMap = new HashMap();
			userMetaMap.put("theme", (String)map.get("theme"));
			userMetaMap.put("homePage", (String)map.get("homePage"));
			userMetaMap.put("showTodo", (String)map.get("showTodo"));
			userMetaMap.put("showNote", (String)map.get("showNote"));
			userMetaMap.put("showPicture", (String)map.get("showPicture"));
			userMetaMap.put("showAccount", (String)map.get("showAccount"));
			userMetaMap.put("showFeed", (String)map.get("showFeed"));
			userMetaMap.put("showDocument", (String)map.get("showDocument"));
			if(Constants.ROLE_CODE_3.equals(paramUser.getRole())){
				userMetaMap.put("showSystem", Constants.CHECK_FALSE);
			}else{
				userMetaMap.put("showSystem", Constants.CHECK_TRUE);
			}
			userMetaService.insert(userId, userMetaMap);

			// 创建文档目录
			String uploadFilePath = ServletHelp.getRealPath((HttpServletRequest)map.get("request"),
					MessageUtils.setParamMessage(Constants.UPLOAD_FILE_PATH, new String[]{userId}));
			FileUtils.createDirs(uploadFilePath);
			
			// 创建图片目录
			String uploadPicturePath = ServletHelp.getRealPath((HttpServletRequest)map.get("request"),
					MessageUtils.setParamMessage(Constants.UPLOAD_PICTURE_PATH, new String[]{userId}));
			FileUtils.createDirs(uploadPicturePath);
			// 缩略图目录
			FileUtils.createDirs(uploadPicturePath+"/"+Constants.THUMBNAIL);
			
			// 创建订阅目录
			String feedFilePath = ServletHelp.getRealPath((HttpServletRequest)map.get("request"),
					MessageUtils.setParamMessage(Constants.FEED_FILE_PATH, new String[]{userId}));
			FileUtils.createDirs(feedFilePath);
		}
		
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", isSuccess);
		res.put("message", errorMsg);
		return res;
	}

	/**
	 * 重置密码
	 * @param map 参数
	 */
	@SuppressWarnings("unchecked")
	public JSONObject resetPwd(Map map) throws Exception{
		// 返回结果
		boolean isSuccess = true;
		String message = "";

		// 用户ID
		String userId = (String)map.get("userId");
		// 密码
		String email = (String)map.get("email");
		// 验证码
		String verifyCode = (String)map.get("verifyCode");
		String verifyCodeInSession = (String)map.get("verifyCodeInSession");
		
		// 验证码验证
		if (!verifyCode.equals(verifyCodeInSession)) {
			isSuccess = false;
			message = Constants.E_VERIFY_CODE;
		}
		
		// 用户存在验证
		List<User> userList = null;
		if (StringUtils.isNotEmpty(userId) && StringUtils.isNotEmpty(email)) {
			// 取得用户
			User paramUser = new User();
			paramUser.setUserId(userId);
			paramUser.setEmail(email);
			userList = this.selectByCriteria(paramUser);
		}
		if (userList == null || userList.size() != 1) {
			isSuccess = false;
			message = Constants.E_FAILURE_RESETPWD;
		}
		
		if(isSuccess){
			// 取得当前用户
			User user = userList.get(0);
			// 生成随机密码
			String newPassword = RandomStringUtils.random(6, true, true);
			// 发送邮件
			String title = "密码重置";
			String content = user.getUserId() + "，您好：<br/>您的新密码是："
					+ newPassword;
			boolean rs = ServletHelp.sendEmail(email, title, content);
			if (rs) {
				// 重置密码
				User paramUser = new User();
				paramUser.setUserId(userId);
				paramUser.setPassword(MD5Utils.getMD5String(newPassword));
				this.update(paramUser);
			} else {
				isSuccess = false;
				message = Constants.E_SEND_EMAIL;
			}
		}
		

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", isSuccess);
		res.put("message", message);
		return res;
	}
	
	/**
	 * 根据用户获得用户基本信息和配置信息
	 * */
	private User getUserWithMetaByUserId(String userId){
		// 当前登录User
		User currentUser = this.selectByPrimaryKey(userId);
		// 查询当前用户配置信息
		UserMeta userMeta = new UserMeta();
		userMeta.setUserId(userId);
		List<UserMeta> userMetaList = userMetaService.selectByCriteria(userMeta);
		Map<String, String> userMetaMap = new HashMap<String, String>();
		if(null != userMetaList){
			for (UserMeta temp : userMetaList) {
				userMetaMap.put(temp.getMetaKey(), temp.getMetaValue());
			}
			currentUser.setUserMeta(userMetaMap);
		}
		return currentUser;
	}
}
